﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using Dapper;


namespace YinLong.Orm.Sqlite
{
    public class SqliteHelper
    {
        /// <summary>
        /// 数据库地址默认system.db
        /// </summary>
        public static string DbPath { get; set; } = AppDomain.CurrentDomain.BaseDirectory + "system.db";
        /// <summary>
        /// 数据库密码(可以不设置)
        /// </summary>
        public static string DbPassWord { get; set; }
        private static object _obj = new object();
        public static SQLiteConnection Connection
        {
            get
            {
                SQLiteConnectionStringBuilder sb = new SQLiteConnectionStringBuilder();
                sb.DataSource = DbPath;
                sb.Version = 3;
                if (!string.IsNullOrEmpty(DbPassWord))
                {
                    sb.Password = DbPassWord;
                }
              
                SQLiteConnection connection = null;

                if (connection == null)
                {
                    lock (_obj)
                    {
                        if (connection == null)
                        {
                            connection = new SQLiteConnection(sb.ToString());
                        }
                    }
                }

                return connection;
            }
        }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <returns></returns>
        public static bool Initialize(List<string> CreateTableSql)
        {
            using (var con = Connection)
            {
                if (!File.Exists(DbPath))
                {
                    SQLiteConnection.CreateFile(DbPath);
                    foreach (var item in CreateTableSql)
                    {
                        con.Execute(item);
                    }
                }

                return true;
            }
        }

        public static bool Open()
        {
            try
            {
                using (var con = Connection)
                {
                    con.Execute("select count(*) from sqlite_master where type='table'");
                    return true;
                }
            }
            catch (Exception e)
            {
                return false;
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="newPassWord"></param>
        /// <returns></returns>
        public static bool ChangePass(string newPassWord)
        {
            try
            {
                using (var con = Connection)
                {
                    con.Open();
                    con.ChangePassword(newPassWord);
                    DbPassWord = newPassWord;
                    return true;
                }
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
}